//
//  YJLocationTool.m
//  YaJi
//
//  Created by YiGuo on 2018/11/15.

//

#import "YJLocationTool.h"
#import <MapKit/MapKit.h>



@interface YJLocationTool()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLGeocoder *geocoder;

@end

@implementation YJLocationTool

static YJLocationTool *yjLocation;
+(instancetype)shareinstance{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        yjLocation = [[YJLocationTool alloc] init];
    });
    
    return yjLocation;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        yjLocation = [super allocWithZone:zone];
    });
    return yjLocation;
}

- (id)copyWithZone:(NSZone *)zone
{
    return yjLocation;
}

-(id)init{
    if (self = [super init]){
        _locationManager = [[CLLocationManager alloc] init];
        _geocoder = [[CLGeocoder alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;//精准度
    }
    return self;
}

-(BOOL)startLocation{
    
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized)) {
        
        // 定位管理器 开始更新位置
        [self.locationManager requestWhenInUseAuthorization];//前台
        //            [self.locationManager requestAlwaysAuthorization];
        [self.locationManager startUpdatingLocation];
        return YES;
    }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        NSLog(@"定位服务当前可能尚未打开!");
        return NO;
    }else{
        return NO;
    }

}

#pragma mark - 定位管理器 代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations;{
    // 1.既然已经定位到了用户当前的经纬度了,那么可以让定位管理器 停止定位了
    [_locationManager stopUpdatingLocation];
    // 2.然后,取出第一个位置,根据其经纬度,通过CLGeocoder反向解析,获得该位置所在的城市名称
    CLLocation *loc = [locations firstObject];
    
    [self getAddressByLocation:loc];
}

#pragma mark 根据坐标取得地名
-(void)getAddressByLocation:(CLLocation *)location
{
    __weak __typeof(self)weakSelf = self;
    //反地理编码
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks firstObject];
        NSString *locality = placemark.locality;

        //NSString *postalCode = placemark.postalCode;
        
        if (!locality) {
            //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
            locality = placemark.administrativeArea;
        }
        
        NSRange range = [locality rangeOfString:@"市"];
        if (range.length > 0) {
            // 将最后一个字符【市】去掉
            locality = [placemark.locality substringToIndex:placemark.locality.length - 1]; // 城市
        }
        
        CLLocationCoordinate2D coordinate = location.coordinate;
        
        NSLog(@"longitude:%lf latitude:%lf",coordinate.longitude, coordinate.latitude);
        
        NSString *longitudeStr = [NSString stringWithFormat:@"%lf",coordinate.longitude];
        NSString *latitudeStr = [NSString stringWithFormat:@"%lf",coordinate.latitude];
        
        if (self.blockType == YJLocationBlockTypeAreaName) {
            self.areaNameBlock(placemark.administrativeArea, placemark.locality, placemark.subLocality, error);
        }else{
            self.loctionBlock(longitudeStr, latitudeStr, locality, error);
        }
        
        
        
        //NSLog(@"locality : %@", locality);
        if ([weakSelf.delegate respondsToSelector:@selector(didFinishLocationsCity:error:)]) {
            [weakSelf.delegate didFinishLocationsCity:locality error:error];
        }
        
        }];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
            // 用户还未决定
        case kCLAuthorizationStatusNotDetermined:
        {
            NSLog(@"用户还未决定");
            break;
        }
            // 访问受限
        case kCLAuthorizationStatusRestricted:
        {
            NSLog(@"访问受限");
            break;
        }
            // 定位关闭时和对此APP授权为never时调用
        case kCLAuthorizationStatusDenied:
        {
            // 定位是否可用（是否支持定位或者定位是否开启）
            if([CLLocationManager locationServicesEnabled])
            {
                NSLog(@"定位开启，但被拒");
            }else
            {
                NSLog(@"定位关闭，不可用, 请在设置中打开定位服务选项");
            }
            //            NSLog(@"被拒");
            break;
        }
            // 获取前后台定位授权
        case kCLAuthorizationStatusAuthorizedAlways:
            //        case kCLAuthorizationStatusAuthorized: // 失效，不建议使用
        {
            NSLog(@"获取前后台定位授权");
            break;
        }
            // 获得前台定位授权
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        {
            NSLog(@"获得前台定位授权");
            break;
        }
    }
}
/*网络获取定位*/
+(NSDictionary *)_yjGetWANIP {
    
    //通过淘宝提供的服务，定位WAN的IP
    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
    NSData *data = [NSData dataWithContentsOfURL:ipURL];
    NSDictionary *locationDict = [NSDictionary dictionary];
    if (data !=nil) {
        locationDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    }
    return locationDict;
}

-(void)dealloc  {
    NSLog(@"");
}

@end
